const http = require("http");
const fs = require('fs');
const path = require("path");
const { URL } = require("url");

http.createServer((req , res) => {
    console.log(req.method);
    console.log(req.url);
    switch(req.method) {
        case "GET":
            getRes(req, res);
            break;
        case "POST":
            postData(req, res);
            break;
        case 'DELETE':
            deleteData(req, res);
            break;
        case "PUT":
            updateData(req, res);
            break;
    }
    if(req.method === 'GET') {
        console.log("方法是get");
    }
    
}).listen(3000);
console.log("server is listen 3000");

function getRes(req , res) {
    let urlObj = new URL(req.url, "http://192.168.42.166:3000");
    console.log(urlObj);
    
    let pageName = '';
    let id = urlObj.searchParams.get("id");
    switch(urlObj.pathname) {
        case '/': 
            pageName = "login.html"
            break;
        case '/list':
            pageName = "list.html"
            break;
        case '/detail':
            res.end("this is detail page" + id);
            return;
        default: 
            pageName = '404.html'
            break;
    }
    let filePath = path.join(__dirname , pageName);
    let data = fs.readFileSync(filePath);
    res.end(data);
}
function postData(req, res) {
    res.end("this is post request");
}
function deleteData(req, res) {
    res.end("this is delete request");

}
function updateData(req, res) {
    res.end("this is post request");
}